﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hotnet.Dal.NSDalPicture;
using Hotnet.Entity;
using Ninject.Core;
using System.Data.Common;
using Hotnet.Biz.Properties;
using Hotnet.Biz.NSBizCommon;
using Hotnet.Entity.Enum;
using Hotnet.Biz.NSBizVideo;
using Hotnet.Entity.Search;

namespace Hotnet.Biz.NSBizPicture
{
	public class BizPictureGroup : BaseBiz<PictureGroup>
	{
		private static DalPictureGroup db = new DalPictureGroup();
		private static PictureGroup[] nullPictureGroup = new PictureGroup[0];

		private BizPicture _BizPicture;
		private BizPicture BizPicture
		{
			get
			{
				if (_BizPicture == null)
					_BizPicture = new BizPicture();
				return _BizPicture;
			}
		}
		private BizPictureGroupXTag _BizPictureGroupXTag;
		private BizPictureGroupXTag BizPictureGroupXTag
		{
			get
			{
				if (_BizPictureGroupXTag == null)
					_BizPictureGroupXTag = new BizPictureGroupXTag();
				return _BizPictureGroupXTag;
			}
		}
		private BizBigEye _BizBigEye;
		private BizBigEye BizBigEye
		{
			get
			{
				if (_BizBigEye == null)
					_BizBigEye = new BizBigEye();
				return _BizBigEye;
			}
		}
		private BizSourceFrom _BizSourceFrom;
		private BizSourceFrom BizSourceFrom
		{
			get
			{
				if (_BizSourceFrom == null)
					_BizSourceFrom = new BizSourceFrom();
				return _BizSourceFrom;
			}
		}
		private BizPictureCategory _BizPictureCategory;
		private BizPictureCategory BizPictureCategory
		{
			get
			{
				if (_BizPictureCategory == null)
					_BizPictureCategory = new BizPictureCategory();
				return _BizPictureCategory;
			}
		}

		private BizTag _BizTag;
		private BizTag BizTag
		{
			get
			{
				if (_BizTag == null)
					_BizTag = new BizTag();
				return _BizTag;
			}
		}

		private BizVideo _BizVideo;
		private BizVideo BizVideo
		{
			get
			{
				if (BizVideo == null)
					_BizVideo = new BizVideo();
				return _BizVideo;
			}
		}


		public BizPictureGroup() : base(db) { }

		public override PictureGroup[] List()
		{
			var groupList = db.List().OrderBy(group => group.OrderInCategory).ToArray();
			return groupList;
		}

		/// <summary>
		/// 删除组,包括组中的图片
		/// </summary>
		/// <param name="id"></param>
		public override void Delete(int id)
		{
			//先删图片
			BizPicture.DeleteAllByGroupId(id);
			//删除组对应的Tag
			BizPictureGroupXTag.DeleteAllByGroupID(id);
			//最后删组
			base.Delete(id);
		}

		/// <summary>
		/// 删除分类下的所有组,包括组中的图片
		/// </summary>
		/// <param name="categoryId"></param>
		public void DeleteAllByCategoryId(int categoryId)
		{
			//using (DbTransaction tran = dalPictureGroup.BeginTransaction())
			//{
			//查询出指定分类下的所有组
			var groups = db.ListBy(pg => pg.CategoryID == categoryId);
			foreach (var group in groups)
			{
				//循环删除各个组下的所有图片
				BizPicture.DeleteAllByGroupId(group.GroupID);
				//删除各个组下的所有Tag
				BizPictureGroupXTag.DeleteAllByGroupID(group.GroupID);
			}
			//删除分类下的所有组
			db.DeleteBy(pg => pg.CategoryID == categoryId);
			//    tran.Commit();
			//}
		}


		/// <summary>
		/// 分页获取指定图片分类下的图片组
		/// </summary>
		/// <param name="categoryId"></param>
		/// <param name="pageNo"></param>
		/// <param name="PAGE_SIZE"></param>
		/// <param name="totalCount"></param>
		/// <returns></returns>
		public PictureGroup[] List(int categoryId, int pageNo, int PAGE_SIZE, out int totalCount)
		{
			//取图片组
			PictureGroup[] groupList = db.List(categoryId, pageNo, PAGE_SIZE, out totalCount);
			FillCoverImageInfo(groupList);
			FillBigEyeInfo(groupList);

			return groupList;
		}

		public PictureGroup[] List(SearchPictureCondition condition, int pageNo, int pageSize, out int totalCount,int? isPublished)
		{
			//取图片组
			PictureGroup[] groupList = db.List(condition, pageNo, pageSize, out totalCount,isPublished);
			FillCoverImageInfo(groupList);
			FillBigEyeInfo(groupList);
			return groupList;
		}

		public void UpdateAll(PictureGroup group)
		{
			BizPictureGroupXTag.DeleteAllByGroupID(group.GroupID);
			BizPictureGroupXTag.SaveTags(group.Tags, group.GroupID);
			db.Update(group);
		}

		public override void Insert(PictureGroup group)
		{
			base.Insert(group);
			BizPictureGroupXTag.SaveTags(group.Tags, group.GroupID);
		}

		public PictureGroup[] ListTop(int categoryId, int count)
		{
			var groups = db.ListTop(categoryId, count);
			FillCoverImageInfo(groups);

			return groups;
		}

		/// <summary>
		/// 列出热图
		/// </summary>
		/// <param name="count"></param>
		/// <returns></returns>
		public PictureGroup[] ListHotGroups(int count)
		{
			var groups = db.ListHotGroups(count);
			return groups;
		}

		/// <summary>
		/// 列出最新的图片
		/// </summary>
		/// <param name="dayBefore"></param>
		/// <param name="count"></param>
		/// <returns></returns>
		public PictureGroup[] ListNewestPictureGroup(int dayBefore, int count)
		{
			var groups=db.ListNewestPictureGroup(dayBefore,count);
			FillCoverImageInfo(groups);
			return groups;
		}

		

		/// <summary>
		/// 列出某分类下面的热图
		/// </summary>
		/// <param name="categoryId"></param>
		/// <param name="count"></param>
		/// <returns></returns>
		public PictureGroup[] ListHotGroups(int categoryId, int count)
		{
			var groups = db.ListHotGroups(categoryId, count);
			return groups;
		}

		//TODO　优化，此处取sourceFromID 和 category 都是直接从数据库中获得,需要从缓存中取
		public PictureGroup GetPictureGroupIncludeSourceFrom(int groupId)
		{
			var group = db.Get(groupId);
			group.SourceFrom = BizSourceFrom.Get(group.SourceFromID);
			group.PictureCategory = BizPictureCategory.Get(group.CategoryID);
			return group;
		}

		/// <summary>
		/// 列出推荐图片,db中是按照时间排序,列出最新推荐
		/// </summary>
		/// <param name="count"></param>
		/// <returns></returns>
		public PictureGroup[] ListRecommendPictureGroup(int count)
		{
			var groups = db.ListDefineTypePictureGroup(count, EnumDefineType.我的推荐);
			FillCoverImageInfo(groups);
			return groups;
		}

		/// <summary>
		/// 列出某一分类下面的 推荐图片
		/// </summary>
		/// <param name="categoryId"></param>
		/// <param name="count"></param>
		/// <returns></returns>
		public PictureGroup[] ListRecommendPictureGroup(int categoryId, int count)
		{
			var groups = db.ListDefineTypePictureGroup(categoryId, count, EnumDefineType.我的推荐);
			FillCoverImageInfo(groups);
			return groups;
		}

		/// <summary>
		/// 列出某一分类下面的 大眼睛图片
		/// </summary>
		/// <param name="categoryId"></param>
		/// <param name="count"></param>
		/// <returns></returns>
		public PictureGroup[] ListCategoryBigEyePictureGroup(int categoryId, int count)
		{
			var groups = db.ListDefineTypePictureGroup(categoryId, count, EnumDefineType.分类轮换);
			FillCoverImageInfo(groups);
			return groups;
		}

		public PictureGroup[] ListRecommendPictureGroup(int pageNo, int PAGE_SIZE, out int totalCount, EnumOrder order)
		{
			PictureGroup[] groups= db.ListRecommendPictureGroup(pageNo, PAGE_SIZE, out totalCount, order);
			FillCoverImageInfo(groups);
			return groups;
		}


		/// <summary>
		/// 给外部的人用
		/// </summary>
		/// <param name="tags"></param>
		/// <param name="groupId"></param>
		/// <param name="count"></param>
		/// <returns></returns>
		public PictureGroup[] ListReferenceGroupsByTags(IList<string> tags, int count,bool isWhenNotEnoughAdd)
		{
			PictureGroup[] groups = isWhenNotEnoughAdd ? db.PictureGroupSupplyWhenNotEnough(db.ListReferenceGroupsByTags(tags, count), count) : db.ListReferenceGroupsByTags(tags, count);
			FillCoverImageInfo(groups);
			return groups;
		}

		public PictureGroup[] ListReferenceGroupsByTags(string tags, int count, bool isWhenNotEnoughAdd)
		{
			if (string.IsNullOrEmpty(tags))
				return nullPictureGroup;
			IList<string> listTag = tags.Split(new string[] { " " },StringSplitOptions.RemoveEmptyEntries);
			return ListReferenceGroupsByTags(listTag, count, isWhenNotEnoughAdd);
		}

		/// <summary>
		/// 根据tagNames列出图片组,分页显示
		/// </summary>
		/// <param name="pageSize"></param>
		/// <param name="pageNo"></param>
		/// <param name="totalCount"></param>
		/// <param name="tagNameList"></param>
		/// <returns></returns>
		public PictureGroup[] ListReferenceGroupsByTags(int pageSize, int pageNo, out int totalCount, IList<string> tagNameList)
		{
			PictureGroup[] groups = db.ListReferenceGroupsByTags(pageSize, pageNo, out totalCount, tagNameList);
			FillCoverImageInfo(groups);
			return groups;
		}

		/// <summary>
		/// 根据图片的Tag取相关的图片组
		/// </summary>
		/// <param name="groupId"></param>
		/// <param name="count"></param>
		/// <returns></returns>
		public PictureGroup[] ListReferenceGroupsByGroupID(int groupId, int count)
		{
			List<string> tagIdList = BizPictureGroupXTag.ListTagNamesByGroupID(groupId);
			PictureGroup[] groups = db.ListReferenceGroupsByTags(tagIdList, groupId, count);
			FillCoverImageInfo(groups);

			return groups;
		}

		/// <summary>
		/// 列出图片分类点击靠前的图片组
		/// </summary>
		/// <param name="topNumber">top 数</param>
		/// <returns></returns>
		public IEnumerable<IGrouping<int, ViewPictureGroup>> ListTopXPictureGroupByCategory(int topNumber)
		{
			ViewPictureGroup[] pictureGroups = db.ListTopXPictureGroupByCategory(topNumber);
			IEnumerable<IGrouping<int, ViewPictureGroup>> groupResult = pictureGroups.GroupBy<ViewPictureGroup, int>(x => x.CategoryID);
			return groupResult;
		}

		/// <summary>
		/// 增加点击数
		/// </summary>
		/// <param name="groupId"></param>
		/// <param name="clickCount"></param>
		public void IncreaseClickCount(int groupId, int clickCount)
		{
			db.UpdateSelfDefine(new PictureGroup
			{
				GroupID = groupId,
				ClickCount = ++clickCount
			}, false, false);
		}

		public PictureGroup GetAll(int id)
		{
			var group = db.Get(id);
			var tags = BizPictureGroupXTag.GetTagStringsByGroupID(id);
			group.Tags = tags;
			return group;
		}

		/// <summary>
		/// 为每个图片组获得封面图片对象
		/// </summary>
		/// <param name="pictureGroup"></param>
		public void FillCoverImageInfo(PictureGroup[] pictureGroup)
		{
			//取出每个图片组的封面图片
			Picture[] coverPictures = BizPicture.ListInIDs(pictureGroup.Select(x => x.CoverImageID==null?0:x.CoverImageID.Value).ToArray());
			foreach (var group in pictureGroup)
			{
				if (group.CoverImageID == null || group.CoverImageID == 0)
				{
					group.CoverImage = new Picture();
					group.CoverImage.ThumbnailPath = Settings.Default.NoPictureLogoPath;
				}
				else
				{
					group.CoverImage = coverPictures.FirstOrDefault(x => x.GroupID == group.GroupID);
					group.CoverImagePath =Settings.Default.UploadFolder+ coverPictures.FirstOrDefault(x => x.GroupID == group.GroupID).ThumbnailPath;
					if (group.CoverImage == null)
					{
						var g = db.Get(group.GroupID);
						g.CoverImageID = 0;
						db.Update(g);
						group.CoverImage = new Picture();
						group.CoverImage.ThumbnailPath = Settings.Default.NoPictureLogoPath;
					}
					else
					{
						group.CoverImage.ThumbnailPath = Settings.Default.UploadFolder + group.CoverImage.ThumbnailPath;
					}
				}
			}
		}

		/// <summary>
		/// 获取大眼睛信息
		/// </summary>
		/// <param name="pictureGroup"></param>
		public void FillBigEyeInfo(PictureGroup[] pictureGroup)
		{
			//取出图片的大眼睛id
			BigEye[] bigEyes = BizBigEye.ListTop(EnumSystemCategory.图片, int.MaxValue);

			//为每个图片组装载封面图片.
			foreach (var group in pictureGroup)
			{

				var bigEye = bigEyes.FirstOrDefault(x => x.TargetEyeID == group.GroupID);
				group.IsBigEye = (bigEye != null);
				group.BigEyeID = (bigEye == null ? 0 : bigEye.BigEyeID);
			}
		}

	}
}
